<template>
  <el-form :model="form" label-width="120px" ref="form" :rules="rules" @submit.native.prevent>
    <!-- 视频类型选择 -->
    <el-form-item label="类型" prop="type" required>
      <el-select v-model="form.type" @change="handleTypeChange">
        <el-option
          v-for="(option, index) in typeOptions"
          :key="index"
          :label="option"
          :value="option"
        ></el-option>
        <el-option
          :label="newTypeLabel"
          :value="newTypeValue"
          v-if="showNewTypeOption"
        >添加新类型</el-option>
      </el-select>
      <el-input
        v-if="isAddingNewType"
        v-model="newTypeInput"
        placeholder="请输入新类型名称"
        @keyup.enter="addNewType"
      ></el-input>
    </el-form-item>
    <!-- 视频上传 -->
    <el-form-item label="视频" prop="video" required>
      <el-upload
        class="avatar-uploader"
        action="http://localhost:8080/video/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <video v-if="videoUrl" :src="require('@/assets/video/' + videoUrl)"></video>
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <!-- 视频标题输入 -->
    <el-form-item label="视频标题" prop="name" required>
      <el-input type="textarea" :rows="3.8" v-model="form.name" :placeholder="namePlaceholder"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">发布</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import axios from 'axios';
import router from '@/router';

export default {
  data() {
    return {
      form: {
        type: '',
        name: '',
        video: ''
      },
      videoUrl: '',
      typeOptions: ['职场礼仪', '简历撰写', '求职技巧', '职业精神'],
      newTypeInput: '',
      newTypeLabel: '添加新类型',
      newTypeValue: 'new_type',
      showNewTypeOption: true,
      isAddingNewType: false,
      rules: {
        type: [
          { required: true, message: '请选择视频类型', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请填写视频标题', trigger: 'blur' }
        ],
        video: [
          { required: true, message: '请上传视频', trigger: 'blur' }
        ]
      },
      namePlaceholder: '请输入视频标题',
      typeNumberMap: {
        '职场礼仪': 1,
        '简历撰写': 2,
        '求职技巧': 3,
        '职业精神': 4
      }, // 用于存储类型名称和对应编号的映射对象
      newTypeCounter: 5 // 新增类型编号的计数器，初始值为已有类型数量 + 1
    };
  },
  methods: {
    handleTypeChange() {
      if (this.form.type === this.newTypeValue) {
        this.isAddingNewType = true;
        this.form.type = this.newTypeCounter; // 将当前新增类型编号赋值给form.type
        this.typeNumberMap[this.newTypeInput] = this.newTypeCounter; // 将新类型名称和编号添加到映射对象中
        this.newTypeCounter++; // 递增新增类型编号计数器
      } else {
        this.isAddingNewType = false;
        this.form.type = this.typeNumberMap[this.form.type]; // 从映射对象中获取已有类型对应的编号赋值给form.type
      }
    },
    addNewType() {
      if (this.newTypeInput.trim()!== '') {
        this.typeOptions.push(this.newTypeInput);
        // 重新设置form.type为对应的编号，保持一致
        this.form.type = this.newTypeCounter - 1;
        this.typeNumberMap[this.newTypeInput] = this.newTypeCounter - 1; // 更新类型名称和编号的映射关系
        this.isAddingNewType = false;
        this.newTypeInput = '';
      }
    },
    handleAvatarSuccess(res, file) {
      console.log(res.data);
      this.videoUrl = res.data;
      this.form.video = res.data;
      console.log('../assets/video/' + this.videoUrl);
    },
    beforeAvatarUpload(file) {
      const isVideoFormatOk = ['video/mp4', 'video/mpeg', 'video/quicktime'].includes(file.type);
      const isLt20M = file.size / 1024 / 1024 < 20;

      if (!isVideoFormatOk) {
        this.$message.error('上传视频格式只能是mp4、mpeg、quicktime格式!');
      }
      if (!isLt20M) {
        this.$message.error('上传视频大小不能超过20MB!');
      }

      return isVideoFormatOk && isLt20M;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          axios.post('http://localhost:8080/video/create', this.form)
           .then((response) => {
              console.log('表单数据提交成功，后端响应：', response);
              // const id = response.data.data;
              this.$message({
                message: '表单数据提交成功！',
                type: 'success',
                duration: 2000
              });
            })
           .catch((error) => {
              console.error('表单数据提交失败，错误信息：', error);
              this.$message({
                message: '表单数据提交失败，请检查网络或稍后重试！',
                type: 'error',
                duration: 2000
              });
            });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
      this.videoUrl = '';
    }
  }
};
</script>

<style scoped>
.avatar-uploader.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader.el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-textarea__inner {
  line-height: 2.5;
}
</style>
